<?php
require_once "../add/TegGenerator.php";
require_once "../add/ClassList.php";
require_once "../add/timer.class.php";
require_once "../include/settings.php";
require_once "../include/global.php";
require_once '../include/DbSimple/Generic.php';
require_once"AddClasses.php";

	 // $conn = dbconn();
	 
	 
				function get_real_prline($tb='stat_in')
				{
					$table=mysql_query("select pr_id as spi from stat_in group by spi");
					$row=mysql_fetch_assoc($table);
					$prline=$row[spi];
					while($row=mysql_fetch_assoc($table))$prline.=','.$row[spi];
					return $prline;
				}
				
				
				//cool
				function get_real_pr_gr($prline)//в таком порядке идет в таблу статина(в шапу),структура дерево, на классах
				{
					$arr=array();
					
					$table=mysql_query("select p.name as pname,p.id as pid,g.name as gname,g.id as gid, g.gorder as gor
						from pr_gr as pg join projects as p join groups as g where 
						pg.pr_id=p.id and pg.gr_id=g.id and pr_id in ($prline) 
						order by gor,gname,pname");
						
						if(!$row=mysql_fetch_assoc($table))return 0;
					while(1)
					{
						$cur_gi=$row[gid];
						$gr=new RealGroup($row[gid],$row[gname]);
						
						while(1)
						{	
							if($cur_gi==$row[gid])
							{
								$gr->fill_arr_projs($row[pid],$row[pname]);
								$flag=($row=mysql_fetch_assoc($table));
								if(!$flag)break;
							}
							else 
							{
								break;
							}
						}
						
						array_push($arr,$gr);
						if(!$flag)break;
					}
					return $arr;
				}
				//////////////////////////
				function get_real_datetimes($prline)
				{
					$arr=array();
					
					$table=mysql_query("select date(s.datetime)as date,time(s.datetime)as time,WEEKDAY(s.datetime) as wday, 
												s.pr_id as pi,s.`call` as `call`,
												s.`min` as `min`,s.waste as waste,s.service as service, s.withoutIVR as withoutIVR, p.name as name from stat_in as s 
												join projects as p where s.pr_id=p.id and s.pr_id in ($prline)
												 order by date(s.datetime) desc,time(s.datetime),p.name");
				
				
						if(!$row=mysql_fetch_assoc($table))return 0;
					$cnt = 0;
					while(1)
					{
						// if ($cnt==0)
							// print_r($row);
						// $cnt++;
						$sd=new StDate($row[date],$row[wday]);
						
						while(1)
						{	
							if($sd->date==$row[date])
							{	
								$sdt=new StDateTime($row[date],$row[time]);
								while(1)
								{
									if(($sdt->date==$row[date])&&($sdt->time==$row[time]))
									{
										$sdt->fill_arr_data($row[call],$row[min],$row[waste],$row[service],$row[withoutIVR],$row[pi]);
										$flag=($row=mysql_fetch_assoc($table));
										if(!$flag)break;
									}
									else break;
								}
								$sdt->count_com_group_data();
								$sd->fill_arr_datetimes($sdt);
								if(!$flag)break;
							}
							else 
							{
								break;
							}
						}
						
						$sd->count_date_data();
						$sd->count_com_group_data();

						array_push($arr,$sd);
						if(!$flag)break;
					}
					return $arr;
				}
				
				
					//////////////////////////
				function get_real_com_datetimes()
				{
					$arr=array();
					
					$table=mysql_query("select date(s.datetime)as date,time(s.datetime)as time,WEEKDAY(s.datetime) as wday, 
												s.`call` as `call`,
												s.`min` as `min`,s.waste as waste,s.service as service, s.withoutIVR as withoutIVR from stat_in_com as s 
												order by date(s.datetime) desc,time(s.datetime)");
				
				
						if(!$row=mysql_fetch_assoc($table))return 0;
					while(1)
					{
						$sd=new StDate($row[date],$row[wday]);
						
						while(1)
						{	
							if($sd->date==$row[date])
							{	
								$sdt=new StDateTime($row[date],$row[time]);
								$sdt->fill_arr_data($row[call],$row[min],$row[waste],$row[service],$row[withoutIVR],$row[pi]);

								$flag=($row=mysql_fetch_assoc($table));
								// if(!$flag)break;
								
							}
							else 
							{
								break;
							}
							
							$sd->fill_arr_datetimes($sdt);
								if(!$flag)break;
						}
						
						$sd->count_date_data();
						array_push($arr,$sd);
						if(!$flag)break;
					}
					return $arr;
				}
	/////////////////////////////////////////////считабельные
		
				function SUM2(&$call,$pricall)
				{
					if($pricall>=0)
					{
						if($call<0)$call=0;
						$call+=$pricall;
					}
				}
				
				
				function AVG2(&$service,$pricall,$priservice)
				{
					if($priservice>=0)
					{	
						if($service<0)$service=0;
						if($pricall>=0)$service+=$pricall*$priservice;
					}
				}
				// /////////////////////////////////////////////////////////
					function summarize_StData($arr_st_datas) //sum ||avg_q взависимости от контекста
				{
						$arr=array();
						$num=count($arr_st_datas[0]);//количество проектов в гр=кол-во классов дата в данном arr_st_datetimes
						
							
							for($i=0;$i<$num;$i++)
							{
									$call=-1;
									$min=-1;
									$waste=-1;
									$service=-1;
									$withoutIVR = -1;
							
											foreach($arr_st_datas as $data)
										{
											// echo $data->pi.'<br>';
											// echo $data->withoutIVR.'<br>';
											// if ($data->pi=='136')
												// echo $data->withoutIVR;
											SUM2($call,$data[$i]->call);
											SUM2($min,$data[$i]->min);
											SUM2($withoutIVR,$data[$i]->withoutIVR);
											AVG2($waste,$data[$i]->call,$data[$i]->waste);
											AVG2($service,$data[$i]->withoutIVR,$data[$i]->service);
										}
										if($call>=0)
										{
											if($call==0)
											{
												$waste=0;
												$service=0;
											}
											else
											{								
												$waste/=$call;
												if ($withoutIVR>=0)
													$service/=$withoutIVR;
											}
										}
									array_push($arr,new StData($call,$min,$waste,$service,$withoutIVR));
							}
					return $arr;
				}
				
		////////////////////////////////////////////////////////////////////////////////////////////////////////////
				
				function summarize_Itogo($arr_st_datas) //sum ||avg_q взависимости от контекста
				{
					$arr=array();
						$num=count($arr_st_datas[0]);//количество проектов в гр=кол-во классов дата в данном arr_st_datetimes
						
							for($i=0;$i<$num;$i++)//если com то num=1
							{
									$call=-1;
									$min=-1;
									$waste=-1;
									$service=-1;
									$withoutIVR = -1;
							
											foreach($arr_st_datas as $data)
										{
											$count++;
											SUM2($call,$data[$i]->call);
											SUM2($min,$data[$i]->min);
											SUM2($withoutIVR,$data[$i]->withoutIVR);
											AVG2($waste,$data[$i]->call,$data[$i]->waste);
											AVG2($service,$data[$i]->withoutIVR,$data[$i]->service);
										}
										if($call>=0)
										{
											if($call==0)
											{
												$waste=0;
												$service=0;
											}
											else
											{								
												$waste/=$call;
												if ($withoutIVR>=0)
													$service/=$withoutIVR;
											}
										}
								$std=new StData($call,$min,$waste,$service);
							
								$html_av.=Td(clear_data($std->call/$count),'class=yellow').Td(clear_data($std->min/$count),'class=yellow').Td(
								clear_data($std->waste),'class=yellow').Td(clear_data($std->service),'class=yellow');
								$html_it.=Td(clear_data($std->call)).Td(clear_data($std->min)).Td_n(2);
								$count=0;
							}
							////////////
							global$trh;
							return Tr($html_av,'class="average"'.$trh).Tr($html_it,$trh);
							
				}
					//////////////////////
								function clear_data($data)
						{
							if($data<0)
							{
								return "";
							}
							else
							{
								return round($data);
							}
						}
				
						//////////////
						function change_delimiter($str,$del1,$del2)
						{
							// $arr=array();
							list($h,$m,$s)= preg_split ('/'.$del1.'/', $str);
							// $arr= preg_split ("/:/", $str);
							return $h.$del2.$m.$del2.$s;
						}
		
						function apgrait_time($tformat)
						{
							list($h,$m,$s)=preg_split('/:/',$tformat);
							return $h.'-'.fun($h+1).br();
						}
						
											function fun($num)//фан
										{
											if($num<10)return '0'.$num;
											else return $num;
										}
										
										
		/////////////////////////////////////////////////
			function FillGroup($gr,$expose=0)//gr-class RealGroup,уже заполненная;expose=flag(раскрывать?1/0)
		{
			// $w='style=height:48px"';
			$w='style="height:48px;max-width:80px"';
			$itogo=array();
			
			$pl=$gr->get_pline();
				
				if($expose)
				{
					$n=4*$gr->nump;
					foreach($gr->arr_projs as $pr)
					{
						$thead.=Td($pr->name,"colspan=4 id='p$gr->id' class='p' $w");
						// $thead.=Td($pr->name,"colspan=4 pi=$pr->id id='p$gr->id'");
						$mt.=MiniTable();
					}
					$thead=Tr($thead);
				}
				else
				{
					$n=4;
					$mt=MiniTable();
				}
				
				$thead=Tr(Th($gr->name,"colspan=$n class='gname' id='$gr->id'")).$thead.Tr($mt);
				
				
				$dts=get_real_datetimes($pl);

			foreach($dts as $dt)
			{
				if($expose)
				{
					foreach($dt->arr_datetimes as $t)$html_t.=$t->gen_html();
					$html.=Tbody($dt->gen_html(),"class='$dt->date state' align=center").Tbody($html_t,"class='hide changme'align=center");
					$html_t="";
					array_push($itogo,$dt->arr_data);//itogo по кажд проекту
				}
				else
				{
					foreach($dt->arr_datetimes as $t)$html_t.=$t->gen_html_com();

					$html.=Tbody($dt->gen_html_com(),"align=center").Tbody($html_t,"class='hide changme' align=center");
					$html_t="";
					array_push($itogo,$dt->com_data);//$com_data-массив из класса данных
				}
				
				
			}
			///
			
			$thead=Thead($thead);
			$tfoot.=Tfoot(summarize_Itogo($itogo),"align=center");

			return Table($thead.$html.$tfoot,"class='group block $gr->id' id='$gr->id'");
			
		}
		
	////////////////////////////////////////////////////////////////////////////////////
				
			function FillDay()
		{	
			global$trh;
			global$bdname;
			$mt0_4=Img('mt0_4.png');
			$i=0;
			
			$dtarr=get_real_datetimes(get_real_prline("$bdname"));
			foreach($dtarr as $dt)
			{
				$ti=0;
				foreach($dt->arr_datetimes as $t)
				{
					$time=change_delimiter($t->time,':','-');
					$time_cont=apgrait_time($t->time);

					$html_t.=Tr(Td($time_cont,"colspan=4 class='time time$time' "),$trh." index=$ti");
					$ti++;
				}
				$wd=$dt->wday;
				if(($wd==5)||($wd==6))$wdclass='wday1';//css('background-color','#8CE4FF');
				else $wdclass='wday0';//css('background-color','#C5E2E8');
			
				$html.=Tbody(Tr(Th($dt->date,"colspan=4 class='date $wdclass' wday='$dt->wday'"),"index=$i ".$trh)).Tbody(
				$html_t,"class='hide changme' index='$i' align=right");
				$i++;
				$html_t="";
			}
			
			$thead=Thead(Tr(Th("День")).Tr(Td(Img('mt0_4.png','class="invisible"'),'id="empty"'), $trh));
			
			$tfoot=Tfoot(Tr(Td("Среднее",'class= yellow'),'class="average"'.$trh).Tr(Td("Итого"), $trh));
			return Table($thead.$html.$tfoot, 'class="day block"');
		}
		
		
		
			function FillCom()
		{
		
			$itogo=array();
					$n=4;
					$mt=MiniTable();

					$thead=Tr(Th("Общие","colspan=$n class='com'")).Tr($mt);
				
				$dts=get_real_com_datetimes();
			
			foreach($dts as $dt)
			{
					foreach($dt->arr_datetimes as $t)$html_t.=$t->gen_html();

					$html.=Tbody($dt->gen_html(),"align=center").Tbody($html_t,"class='hide changme' align=center");
					$html_t="";
					array_push($itogo,$dt->arr_data);//$com_data-массив из класса данных
			
			}
		
			$thead=Thead($thead);
			$tfoot.=Tfoot(summarize_Itogo($itogo),"align=center");

			return Table($thead.$html.$tfoot,"class='group block'");
		}
	////////////////////////////////////////////////////////////////////////////////////

?>